module(..., package.seeall)
---------------------------------------------------------
--form displays a list of all audio 5
---------------------------------------------------------
function new(sound)
	require "sprite"
	
	local version = "FREE"
	
	local ui = require("ui")
	local util = require("util")
	
	local scrollView = require("scrollView")
	local viewController = require("viewController")
	local tableView = require("tableView")
	local tblMenuItemMain = require("tblMenuItemMain")
	local tblTopNew = require("tblTopNew")
	local tblYeuThich = require("tblYeuThich")
	local tblSearch = require("tableView2")
	local menuGroup = display.newGroup()
	local menuGroupTop = display.newGroup()
	local tapSound = audio.loadSound( "tapsound.wav" )
	
	local categories = nil
	local menus = nil
	
	local Waiting = nil
	local theTimer
	local stop = false
	-----------------------------------------------------------
	--facebook
	local appId  = "205817059502566"
	-- Facebook Commands
	local fbCommand	-- forward reference
	local LOGOUT = 1
	local SHOW_DIALOG = 2
	local POST_MSG = 3
	local POST_PHOTO = 4
	local GET_USER_INFO = 5
	local GET_PLATFORM_INFO = 6
	-----------------------------------------------------------
	local facebook = require("facebook")
	local json = require("json")
	-----------------------------------------------------------
	local CW = display.contentWidth
	local CH = display.contentHeight
	local SOX = 0--display.screenOriginX
	local SOY = 0--display.screenOriginY
	-----------------------------------------------------------
	local function showAd_Android(event)
		-- Is the url a remote call?
		if string.find(event.url, "android_ad.html", 1, false) then
			return true
		else
			system.openURL( string.gsub(event.url, "Corona:", "") )
			-- Refresh ad
			removeAd()
			createAd(false)
			return true
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	local function showAd_Apple(event)
		-- Is the url a remote call?
		if string.find(event.url, "http://", 1, false) == 1 then
			-- Is it a call to the admob server?
			if string.find(event.url, "c.admob.com", 1, false) ~= nil then
				-- an actual click on an ad, so open in Safari
				system.openURL(event.url)
				-- Refresh ad
				removeAd()
				createAd(false)
			end
		else
			return true
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function createAd(showOnTop)
		if version == "FREE" then
			local adfile = "apple_ad.html"
			local sizeX = 320
			local sizeY = 48
			local posX = (CW - sizeX) / 2
			-- round the Y position to remove the 1px gap
			-- between the bottom of the ad the bottom of the screen
			local posY = showOnTop and SOY or round(CH - SOY - sizeY)
		 
			native.cancelWebPopup()
			
			if isAndroid then
				adfile = "android_ad.html"
				native.showWebPopup(posX, posY, sizeX, sizeY, adfile,
					{
						baseUrl = system.ResourceDirectory,
						hasBackground = false,
						urlRequest = showAd_Android
					}
				)
			elseif system.getInfo("environment") == "simulator" then
				dummy = display.newRect(posX, posY, sizeX, sizeY)
				dummy.alpha = 0.81
				dummy:setFillColor(0, 0, 0)
			else
				native.showWebPopup(posX, posY, sizeX, sizeY, adfile,
					{
						baseUrl = system.ResourceDirectory,
						hasBackground = false,
						urlRequest = showAd_Apple
					}
				)
			end
		end	
	end
	 -----------------------------------------------------
	--
	-----------------------------------------------------
	function removeAd()
		--ads.hide()
		native.cancelWebPopup()
		if dummy then
			dummy:removeSelf()
			dummy = nil
		end
	end
	-----------------------------------------------------------
	function listener( event )
		if ( "session" == event.type ) then
			if event.phase ~= "login" then
				-- Exit if login error
				native.showAlert("Error connecting to the network.")
				return
			end
			-- The following displays a Facebook dialog box for posting to your Facebook Wall
			if fbCommand == SHOW_DIALOG then
				facebook.showDialog( {action="stream.publish"} )
			end
			-- Request the Platform information (FB information)
			if fbCommand == GET_PLATFORM_INFO then
				facebook.request( "platform" )		-- **tjn Displays info about Facebook platform
			end
			-- Request the current logged in user's info
			if fbCommand == GET_USER_INFO then
				facebook.request( "me" )
			--	facebook.request( "me/friends" )		-- Alternate request
			end
			-- This code posts a photo image to your Facebook Wall
			--
			if fbCommand == POST_PHOTO then
				local attachment = {
					name = "1001 Mon an Viet Nam!",
					link = "http://itunes.apple.com/vn/app/vietnamese-food/id512078085?mt=8",
					caption = "1001 Mon an Viet Nam",
					description = "Cam nang dau bep chuyen nghiep giup ban co duoc nhung mon an ngon nhat." ..
					" Tai ung dung tren App store",
					picture = "http://www.azsoft.com.vn/Upload/image/nauan3.PNG",
					actions = json.encode( { { name = "Chi tiet", link = "http://itunes.apple.com/vn/app/vietnamese-food/id512078085?mt=8" } } )
				}
				facebook.request( "me/feed", "POST", attachment )		-- posting the photo
			end
			
			-- This code posts a message to your Facebook Wall
			if fbCommand == POST_MSG then
				local time = os.date("*t")
				local postMsg = {
					message = "Game Pikachu Noel"
				}
				facebook.request( "me/feed", "POST", postMsg )		-- posting the message
			end
		-----------------------------------------------------------------------------------------
		elseif ( "request" == event.type ) then
			-- event.response is a JSON object from the FB server
			local response = event.response
			if ( not event.isError ) then
				response = json.decode( event.response )
				if fbCommand == GET_USER_INFO then
					--		
				elseif fbCommand == POST_PHOTO then
					native.showAlert("You have to share information on Facebook.")				
				elseif fbCommand == POST_MSG then
					native.showAlert("You have to share information on Facebook.")
				else
				end
			else
				native.showAlert(event.response)
			end
		elseif ( "dialog" == event.type ) then
		end
	end
	
	function onShareFaceBook()
		fbCommand = POST_PHOTO
		facebook.login(appId, listener, {"publish_stream"} )
	end
	---------------------------------------------
	--
	---------------------------------------------
	function loadLogin()
		local path = system.pathForFile( "login.txt", system.DocumentsDirectory )
		local fh, reason = io.open(path, "r")
		local info = "" --format true|email|pass
		if fh then
		   -- read all contents of file into a string
		   info = fh:read( "*a" )
		   io.close( fh )
		else
			--info = "true|tatuanvn@gmail.com|123"
		end
		if info ~= "" then
			local i = string.find (info, "|")
			local check = string.sub (info, 1, i - 1)
			if check == "true" then
				local j = i
				i = string.find (info, "|", i + 1)
				memberid = string.sub (info, j + 1, i - 1)
			end
		end
		return ""
	end
	---------------------------------------------
	--save info login
	---------------------------------------------
	function saveLogin(memberid, email)
		local path = system.pathForFile( "login.txt", system.DocumentsDirectory )
		-- io.open opens a file at path. returns nil if no file found
		local fh, reason = io.open(path, "w")
		fh:write("true|" .. memberid .. "|" .. email)
		--[[if autoSavePassword then	
			fh:write("true|" .. emaillogin .. "|" .. passwordlogin)
		else
			fh:write("false|" .. emaillogin .. "|" .. passwordlogin)
		end--]]
		io.close( fh )
	end
	
	function onComplete( event )
	end
	-----------------------------------------------------
	--Form login
	-----------------------------------------------------
	function showFormLogin(grp, name, email)
		if menuGroupLogin == nil then
			menuGroupLogin = display.newGroup()
			grp:insert(menuGroupLogin)
			grp:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			
			bgFormLogin = display.newImage("images/bgFormLogin.png")
			bgFormLogin.x = display.contentWidth/2
			bgFormLogin.y = display.contentHeight/2
			menuGroupLogin:insert(bgFormLogin)
			--Textbox email
			if system.getInfo( "environment" ) == "simulator" then
				txtEmail = display.newRect(64, 194, 200, 28)
				txtEmail:setFillColor(200, 200, 200)
				menuGroupLogin:insert(txtEmail)
			else
				txtEmail = native.newTextField(64, 194, 200, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtEmail.font = native.newFont( native.systemFontBold, inputFontSize )
				txtEmail.inputType = "email"
				if email then
					txtEmail.text = email
				end
				menuGroupLogin:insert(txtEmail)
			end
			--Textbox mat khau
			if system.getInfo( "environment" ) == "simulator" then
				txtPass = display.newRect(64, 260, 200, 28)
				txtPass:setFillColor(200, 200, 200)
				menuGroupLogin:insert(txtPass)
			else
				txtPass = native.newTextField(64, 260, 200, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtPass.font = native.newFont( native.systemFontBold, inputFontSize )
				txtPass.isSecure = true
				menuGroupLogin:insert(txtPass)
			end
			
			btnLogin = ui.newButton{
				default = "images/btnLogin.png",
				over = "images/btnLoginOver.png",
				onRelease = function(event)
					--Thuc hien login he thong
					if system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text == nil or txtEmail.text == "") then
						native.showAlert( "", "Địa chỉ email không hợp lệ!", { "OK"}, onComplete)
					else
						local email = "tatuanvn@gmail.com"
						local pass  = "123456"
						
						if system.getInfo( "environment" ) ~= "simulator" then
							email = txtEmail.text
							pass  = txtPass.text
						end
						local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=NALOGIN&email=" .. email .. "&pass=" .. pass)
						
						if xmlTree ~= nil then
							local LOGIN = xml:xmlNodes(xmlTree, "LOGIN")	
							if LOGIN ~= nil then
								for i, xmlNode in pairs(LOGIN) do
									if(xmlNode.Name == "RS") then
										result = xml:xmlValue(xmlNode, "result")
										if result == "OK" then
											memberid = xml:xmlValue(xmlNode, "memberid")
											--Save login
											saveLogin(memberid, email)
											if name == "XemChiTiet" then
												theTimer = timer.performWithDelay(0, function(event)
													--Xoa form login
													cleanGroups(menuGroupLogin, 0)
													menuGroupLogin = nil
												end, 1)
											end
											--Login thanh cong
											if name == "YeuThich" then
												theTimer = timer.performWithDelay(0, function(event)
													--Xoa form login
													cleanGroups(grp, 0)
													grp = nil
													menuGroupLogin = nil
												end, 1)
												showWaiting()
												theTimer = timer.performWithDelay(250, function(event)
													loadYeuThich()
												end, 1)
											end
										end
										if result == "ERPASS" then
											native.showAlert("", "Sai mật khẩu đăng nhập!", {"OK"}, onComplete)	
										end
										if result == "EREMAIL" then
											native.showAlert("", "Email đăng nhập chưa tồn tại!", {"OK"}, onComplete)
										end
									end
								end
							end
						end
					end
				end
			}
			btnLogin.x = display.contentWidth/2 + btnLogin.width/2 + 32
			btnLogin.y = display.contentHeight/2 + 128
			menuGroupLogin:insert(btnLogin)
			
			btnRegister = ui.newButton{
				default = "images/lblRegister.png",
				over = "images/lblRegister.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupLogin, 0)
						menuGroupLogin = nil
						showFormRegister(grp, name)
					end, 1)
				end
			}
			btnRegister.x = display.contentWidth/2 - btnRegister.width/2 + 10
			btnRegister.y = display.contentHeight/2  + 128
			menuGroupLogin:insert(btnRegister)
			
			btnCloseLogin = ui.newButton{
				default = "images/btnCloseLogin.png",
				over = "images/btnCloseLogin.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupLogin, 0)
						menuGroupLogin = nil
					end, 1)
				end
			}
			btnCloseLogin.x = display.contentWidth/2 + bgFormLogin.width/2 - btnCloseLogin.width/2
			btnCloseLogin.y = display.contentHeight/2  - bgFormLogin.height/2 + btnCloseLogin.height/2 - 3
			menuGroupLogin:insert(btnCloseLogin)
		end
	end
	-----------------------------------------------------
	--Form dang ky
	-----------------------------------------------------
	function showFormRegister(grp, name)
		if menuGroupRegister == nil then
			menuGroupRegister = display.newGroup()
			grp:insert(menuGroupRegister)
			grp:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			
			bgFormRegister = display.newImage("images/bgFormRegister.png")
			bgFormRegister.x = display.contentWidth/2
			bgFormRegister.y = display.contentHeight/2 + 12
			menuGroupRegister:insert(bgFormRegister)
			--Textbox email
			if system.getInfo( "environment" ) == "simulator" then
				txtEmail = display.newRect(42, 148, 228, 28)
				txtEmail:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtEmail)
			else
				txtEmail = native.newTextField(42, 148, 228, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtEmail.font = native.newFont( native.systemFontBold, inputFontSize )
				txtEmail.inputType = "email"
				menuGroupRegister:insert(txtEmail)
			end
					
			--Textbox mat khau
			if system.getInfo( "environment" ) == "simulator" then
				txtPass = display.newRect(42, 208, 228, 28)
				txtPass:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtPass)
			else
				txtPass = native.newTextField(42, 208, 228, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtPass.font = native.newFont( native.systemFontBold, inputFontSize )
				txtPass.isSecure = true
				menuGroupRegister:insert(txtPass)
			end
			
			if system.getInfo( "environment" ) == "simulator" then
				txtRePass = display.newRect(42, 264, 228, 28)
				txtRePass:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtRePass)
			else
				txtRePass = native.newTextField(42, 264, 228, 28, fieldHandler )
				txtRePass.font = native.newFont( native.systemFontBold, inputFontSize )
				txtRePass.isSecure = true
				menuGroupRegister:insert(txtRePass)
			end
			
			btnRegister = ui.newButton{
				default = "images/btnRegister.png",
				over = "images/btnRegisterOver.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Thuc hien dang ky
						local email = "tatuanvn@gmail.com"
						local pass  = "123456"
						if system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text == nil or txtEmail.text == "") then
							native.showAlert( "", "Địa chỉ email không hợp lệ!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" and (txtPass.text == nil or txtPass.text == "") then
							native.showAlert( "", "Mật khẩu không hợp lệ!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text ~= txtPass.text == "") then
							native.showAlert( "", "Mật khẩu lần 2 không đúng!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" then
							email = txtEmail.text
							pass  = txtPass.text
						end
						
						local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=NAREGISTER&email=" .. email .. "&pass=" .. pass)
						
						if xmlTree ~= nil then
							local REGISTER = xml:xmlNodes(xmlTree, "REGISTER")	
							if REGISTER ~= nil then
								for i, xmlNode in pairs(REGISTER) do
									if(xmlNode.Name == "RS") then
										result = xml:xmlValue(xmlNode, "result")
										if result == "OK" then
											--Xoa form dang ky
											cleanGroups(menuGroupRegister, 0)
											menuGroupRegister = nil
											showFormLogin(grp, name, email)
										end
										--Loi email (da dang ky hoac email khong hop le)
										if result == "EREMAIL" then
											native.showAlert("", "Email đăng ký đã tồn tại!", { "OK"}, onComplete)
										end
										if result == "ER" then
											native.showAlert("", "Email đăng ký đã tồn tại!", { "OK"}, onComplete)
										end
									end
								end
							end
						end
					end, 1)
				end
			}
			btnRegister.x = display.contentWidth/2 - btnRegister.width/2 - 32
			btnRegister.y = display.contentHeight/2 + bgFormRegister.height/2 - 90
			menuGroupRegister:insert(btnRegister)
			
			btnCloseLogin = ui.newButton{
				default = "images/btnCloseLogin.png",
				over = "images/btnCloseLogin.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupRegister, 0)
						menuGroupRegister = nil
					end, 1)
				end
			}
			btnCloseLogin.x = display.contentWidth/2 + bgFormRegister.width/2 - btnCloseLogin.width/2 - 3
			btnCloseLogin.y = display.contentHeight/2  - bgFormRegister.height/2 + btnCloseLogin.height/2 + 10
			menuGroupRegister:insert(btnCloseLogin)
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onSelectApp( event )
		self = event.target
		timer.performWithDelay(2, function(event)
			system.openURL(moreapp[self.id].linkdown)
		end, 1)
	end
	
	function checkYeuThich(list, menu)
		if list ~= nil and menu ~= nil then
			for i=1, #list do
				if list[i].menuid == menu.menuid then
					return true
				end
			end
		end
		return false
	end
	
	-----------------------------------------------------
	--Hien thi chi tiet menu
	-----------------------------------------------------
	function showMenuDetails(menu)
		if menuGroupDetails == nil then
			menuGroupDetails = display.newGroup()
			menuGroup:insert(menuGroupDetails)
			
			local bg = display.newImage("images/bgViewDetails.png")
			bg.x = display.contentWidth/2
			bg.y = display.contentHeight/2
			menuGroupDetails:insert(bg)
			
			groupDetails = display.newGroup()
			menuGroupDetails:insert(groupDetails)
			
			local bgViewDetailsOver = display.newImage("images/bgViewDetailsOver.png")
			bgViewDetailsOver.x = display.contentWidth/2
			bgViewDetailsOver.y = display.contentHeight/2
			groupDetails:insert(bgViewDetailsOver)
			
			local navBar = display.newImage("images/navBar.png", 0, 0, true)
			navBar.x = display.contentWidth*.5
			navBar.y = navBar.height*0.5
			groupDetails:insert(navBar)
			
			local btnBack = ui.newButton{
				default = "images/btnBack.png",
				over = "images/btnBackOver.png",
				onRelease = function(event)
					if grpVideo ~= nil then
						native.cancelWebPopup()
						cleanGroups(grpVideo, 0)
						grpVideo = nil
					elseif menuGroupLogin ~= nil then
						cleanGroups(menuGroupLogin, 0)
						menuGroupLogin = nil
					elseif menuGroupRegister ~= nil then
						cleanGroups(menuGroupRegister, 0)
						menuGroupRegister = nil
					elseif menuGroupDetails ~= nil then
						timer.performWithDelay(360, function(event)
							native.cancelWebPopup()
							cleanGroups(menuGroupDetails, 0)
							menuGroupDetails = nil
							groupDetails = nil
						end)
					end
				end
			}
			btnBack.x = btnBack.width/2
			btnBack.y = navBar.y
			groupDetails:insert(btnBack)
			
			if (checkYeuThich(listMenuYeuThich, menu) == false) then
				btnYeuThich = ui.newButton{
						default = "images/btnYeuThich.png",
						over = "images/btnYeuThichOver.png",
						onRelease = function(event)
							if memberid == nil then
								showFormLogin(groupDetails, "XemChiTiet")
							else
								local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=NAADDYT&memberid=" .. memberid .. "&menuid=" .. menu.menuid)
								if xmlTree ~= nil then
									local KQ = xml:xmlNodes(xmlTree, "KQ")	
									if KQ ~= nil then
										for i, xmlNode in pairs(KQ) do
											if(xmlNode.Name == "RS") then
												result = xml:xmlValue(xmlNode, "result")
												if result == "OK" then
													if groupTabYeuThich ~= nil then
														--listMenuYeuThich = nil
														cleanGroups(groupTabYeuThich, 0)
														groupTabYeuThich = nil
														listMenuYeuThich[#listMenuYeuThich + 1] = menu
														 menu.yeuthich = true
													end
													native.showAlert("", "Đã thêm vào mục yêu thích!", {"OK"}, onComplete)	
												end
												
												if result == "EX" then
													native.showAlert("", "Thực đơn này đã có trong yêu thích!", {"OK"}, onComplete)	
												end
												
												if result == "ER" then
													native.showAlert("", "Xin vui lòng thực hiện lại!", {"OK"}, onComplete)
												end
											end
										end
									end
								else
									print("Loi ket noi servrt")
								end
							end
						end
					}
				btnYeuThich.x = 300
				btnYeuThich.y = navBar.y
				groupDetails:insert(btnYeuThich)
			else
				btnYeuThich = ui.newButton{
						default = "images/btnYeuThichOver.png",
						over = "images/btnYeuThichOver.png",
						onRelease = function(event) 
						end
					}
				btnYeuThich.x = 300
				btnYeuThich.y = navBar.y
				groupDetails:insert(btnYeuThich)
			end
					
			btnEmail = ui.newButton{
					default = "images/btnEmail.png",
					over = "images/btnEmailOver.png",
					onRelease = function(event)
						--onSendEmailToFriend()
					end
				}
			btnEmail.x = 36
			btnEmail.y = btnYeuThich.y + 66
			groupDetails:insert(btnEmail)
					
			btnFb = ui.newButton{
					default = "images/btnFb.png",
					over = "images/btnFbOver.png",
					onRelease = function(event)
						onShareFaceBook()
					end
				}
			btnFb.x = 36
			btnFb.y = btnEmail.y + 48
			groupDetails:insert(btnFb)
			
			if menu.idvideo ~= nil and menu.idvideo ~= "-1" then
				btnVideo = ui.newButton{
						default = "images/btnVideo.png",
						over = "images/btnVideoOver.png",
						onRelease = function(event)
							if grpVideo == nil then
								grpVideo = display.newGroup()
								groupDetails:insert(grpVideo)
								
								view = display.newRect(160 - 120, 240 - 150, 240, 160)
								view:setFillColor(200, 200, 200)
								grpVideo:insert(view)

								btnClose = ui.newButton{
									default = "images/btnCloseLogin.png",
									over = "images/btnCloseLogin.png",
									onRelease = function(event)
										theTimer = timer.performWithDelay(10, function(event)
											--clear
											native.cancelWebPopup()
											cleanGroups(grpVideo, 0)
											grpVideo = nil
										end, 1)
									end
								}
								btnClose.x = view.x + view.width/2 + 3
								btnClose.y = view.y - view.height/2 - 3
								grpVideo:insert(btnClose)
								
								v = display.newRect(160 - 120 + 2, 240 - 150 + 8, 236, 150)
								v:setFillColor(100, 100, 100)
								grpVideo:insert(v)
								
								local options = {hasBackground=false, baseUrl=system.DocumentsDirectory, urlRequest=playvideo }
								native.showWebPopup(160 - 120 + 2, 240 - 150 + 8, 236, 150, "http://" .. serverConnect .. "/server.ashx?action=NAVIDEO&idvideo=" .. menu.idvideo, options )
							end
						end
					}
				btnVideo.x = 284
				btnVideo.y = 151
				groupDetails:insert(btnVideo)
			else
				btnVideo = ui.newButton{
						default = "images/btnVideoNull.png",
						over = "images/btnVideoNull.png",
						onRelease = function(event)
							
						end
					}
				btnVideo.x = 284
				btnVideo.y = 151
				groupDetails:insert(btnVideo)
			end
			
			--Caption
			local text = display.newText(menu.title, 0, navBar.y - 12, native.systemFontBold, 14)
			text:setTextColor(255, 255, 255)
			text.x = display.contentWidth*.5
			groupDetails:insert(text)
			
			local textLoading = display.newText("Loading Picture", 0, navBar.y + 90, native.systemFontBold, 12)
			textLoading:setTextColor(255, 255, 255)
			textLoading.x = display.contentWidth*.5
			groupDetails:insert(textLoading)
			
			--load noi dung
			local url = "http://" .. serverConnect .. "/server.ashx?action=NAMENUCONTENT&menuid=" .. menu.menuid
			
			network.request(url, "GET", function( event )
				if menuGroupDetails then
					if (event.isError) then
						native.showAlert( "", "Please check your internet connect!", { "OK"}, onComplete )
					else
						local result = event.response
						
						--print(result)
						--data
						if result == "NOFREE" then
							native.showAlert( "", "Mon an nay khong duoc chia se!", { "OK"}, onClose)
						else
							local scrollView = scrollView.new{top= btnVideo.y + 32, bottom=136 }
							local lotsOfTextObject = util.wrappedText(result, 60, 14, native.systemFont, {0,0,0} )
							local r = display.newRect(8, 4, lotsOfTextObject.width - 8, lotsOfTextObject.height + 10)
							r:setFillColor(255, 255, 255)
							r.alpha = 0.3
							scrollView:insert(r)
							
							scrollView:insert(lotsOfTextObject)
							lotsOfTextObject.x = 8
							lotsOfTextObject.y = 10
							scrollView:addScrollBar()
							menuGroupDetails:insert(scrollView)
							groupDetails:toFront()
						end
					end
				end
			end
			)
			local downloadImage = function() 
				local function networkListener( event )
					if ( event.isError ) then
						print ( "Network error - download failed" )
					else
						if groupDetails ~= nil then
							image =  display.newImage(menu.menuid .. "_2.png", system.TemporaryDirectory)
							if image ~= nil then
								image.x = 160
								image.y = 120
								groupDetails:insert(image)
							end
						end
					end
				end
				image =  display.newImage(menu.menuid .. "_2.png", system.TemporaryDirectory)
				if image == nil then
					network.download("http://" .. serverConnect .. "/images/" .. menu.menuid .. ".png", "GET", networkListener, menu.menuid .. "_2.png", system.TemporaryDirectory )
				else
					if image ~= nil then
						image.x = 160
						image.y = 120
						groupDetails:insert(image)
					end
				end
			end
			timer.performWithDelay(2, downloadImage)
		end
	end
	-----------------------------------------------------
	--Hien thi man hinh cho khi khoi dong ung dung
	-----------------------------------------------------		
	function loading()
		if Waiting == nil then
			Waiting = display.newImage("images/bg_loading.png")
			Waiting.x = display.contentWidth/2
			Waiting.y = display.contentHeight/2
			menuGroupTop:insert(Waiting)
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function showWaiting()
		if Waiting == nil then
			Waiting = display.newImage("images/waiting.png")
			Waiting.x = display.contentWidth/2
			Waiting.y = display.contentHeight/2
			menuGroupTop:insert(Waiting)
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function closeWaiting()
		if theTimer then
			timer.cancel(theTimer)
		end
		if Waiting then
			Waiting:removeSelf()
			Waiting = nil
		end	
	end
	-----------------------------------------------------
	--Chon xem mot mon an tu categories chinh
	-----------------------------------------------------
	function getCategories(catid)
		if categories ~= nil then
			for i=1, #categories do
				if categories[i].catid == catid then
					return categories[i]
				end
			end
		else
			return nil
		end	
	end
	-----------------------------------------------------
	--Chon xem mot mon an tu categories chinh
	-----------------------------------------------------
	function onOpenMenuItem(event)
		local self = event.target
		if catCurrent ~= nill then
			if catCurrent.menus ~= nill then
				showMenuDetails(catCurrent.menus[self.id])
			end
		end
	end
	-----------------------------------------------------
	--Hien danh sach menu item len view
	-----------------------------------------------------
	function onLoadMenuList(xmlTree, catid)
		local menus = nil
		if catid ~= nil then
			if stop == false then
				local data={}
				local MENU = xml:xmlNodes(xmlTree, "MENU")	
				native.setActivityIndicator( true )
				local n = 1
				for i,xmlNode in pairs(MENU) do
					if(xmlNode.Name == "item") then
						local game = {}
						game.menuid = xml:xmlValue(xmlNode, "id")
						game.title = xml:xmlValue(xmlNode, "title")
						game.description = xml:xmlValue(xmlNode, "des")
						game.idvideo = xml:xmlValue(xmlNode, "idvideo")
						local download = function() 
							local function networkListener( event )
								if ( event.isError ) then
									print ( "Network error - download failed" )
								else
									if game.group ~= nil then
										game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
										if game.group ~= nil and stop == false  then
											game.logo.x = 4 + game.logo.width/2
											game.logo.y = 4 + game.logo.height/2
											game.group:insert(game.logo)
										elseif game.logo ~= nil and stop then
											game.logo:removeSelf()
										end
									end
								end
							end
							game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
							if game.logo == nil then
								network.download("http://" .. serverConnect .. "/smallimages/" .. game.menuid .. ".png", "GET", networkListener, game.menuid .. ".png", system.TemporaryDirectory )
							else
								if game.group ~= nil  and stop == false  then
									game.logo.x = 4 + game.logo.width/2
									game.logo.y = 4 + game.logo.height/2
									game.group:insert(game.logo)
								elseif game.logo ~= nil and stop then
									game.logo:removeSelf()
								end
							end
						end
						timer.performWithDelay(2, download)
						data[n] = game
						n = n + 1
					end
					menus = data
					local cat = getCategories(catid)
					if cat ~= nil then
						cat.menus = menus
					end
				end
			end
		else
			menus = xmlTree
		end
		if menus == nil then
			menus = {}
		end
		native.setActivityIndicator( false ) -- show busy
			
		local topBoundary = 49
		local bottomBoundary = 49
		local myList = tblMenuItemMain.newList{
			data = menus, 
			default = "images/bgitem.png",
			over = "images/bgitem.png",
			onRelease = onOpenMenuItem,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				local item = display.newImage("images/item.png")
				item.x = item.width/2
				item.y = item.height/2
				group:insert(item)

				local text = display.newText(row.title, 0,  10, native.systemFontBold, 15)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				text = display.newText(row.description, 0,  36, "Helvetica", 14)
				text:setTextColor(200, 200, 200)
				text.x = 68 + text.width/2
				group:insert(text)
				
				group.logo =  display.newImage(row.menuid .. ".png", system.TemporaryDirectory)
				if group.logo ~= nil and stop == false  then
					group.logo.x = 4 + group.logo.width/2
					group.logo.y = 4 + group.logo.height/2
					group:insert(group.logo)
				end
				row.group = group	
				return group
			end
		}
		--myList.x = 0
		if(groupMenus ~= nil) then
			cleanGroups(groupMenus, 0)
			groupMenus = nil
		end
		groupMenus = display.newGroup()
		menuGroup:insert(groupMenus)
		groupMenus:insert(myList)
		menuGroupTop:toFront()
	end
	-----------------------------------------------------
	--Thuc hien load danh sach menu thuoc categories
	-----------------------------------------------------
	function onLoadMenuItemList(catid)
		local cat = getCategories(catid)
		if cat ~= nil and cat.menus == nil then
			local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=MNULIST&catid=" .. catid)
			if xmlTree then
				onLoadMenuList(xmlTree, catid)
			end
		else
			if cat ~= nil then
				onLoadMenuList(cat.menus)
			end
		end
		catCurrent = cat;
		closeWaiting()
		
		btnBack.isVisible = true
	end
	-----------------------------------------------------
	--Su kien khi chon mot categories
	-----------------------------------------------------
	function onOpenCategories(event)
		local self = event.target
		setVivibleCategories(false)
		showWaiting()
		theTimer = timer.performWithDelay(250, function(event)
			textHeader.text = categories[self.id].title
			onLoadMenuItemList(categories[self.id].catid)
		end, 1)
	end
	-----------------------------------------------------
	--Hien thi danh muc cac the loai mon an viet nam
	-----------------------------------------------------
	function onLoadedCategories(xmlTree)
		if categories == nil and stop == false then
			local data={}
			local CAT = xml:xmlNodes(xmlTree, "CAT")	
			native.setActivityIndicator( true )
			local n = 1
			for i,xmlNode in pairs(CAT) do
				if(xmlNode.Name == "LOAI") then
					local game = {}
					game.catid = xml:xmlValue(xmlNode, "catid")
					game.title = xml:xmlValue(xmlNode, "cattitle")
					--game.description = xml:xmlValue(xmlNode, "menuname")
					game.icon = xml:xmlValue(xmlNode, "menuid") .. ".png"
					local download = function() 
						local function networkListener( event )
							if ( event.isError ) then
								print ( "Network error - download failed" )
							else
								if game.group ~= nil then
									game.logo =  display.newImage(game.icon, system.TemporaryDirectory)
									if game.group ~= nil and stop == false  then
										game.logo.x = 4 + game.logo.width/2
										game.logo.y = 4 + game.logo.height/2
										game.group:insert(game.logo)
									elseif game.logo ~= nil and stop then
										game.logo:removeSelf()
									end
								end
							end
						end
						game.logo =  display.newImage(game.icon, system.TemporaryDirectory)
						if game.logo == nil then
							network.download("http://" .. serverConnect .. "/smallimages/" .. game.icon, "GET", networkListener, game.icon, system.TemporaryDirectory )
						else
							if game.group ~= nil  and stop == false  then
								game.logo.x = 4 + game.logo.width/2
								game.logo.y = 4 + game.logo.height/2
								game.group:insert(game.logo)
							elseif game.logo ~= nil and stop then
								game.logo:removeSelf()
							end
						end
					end
					timer.performWithDelay(2, download)
					data[n] = game
					n = n + 1
				end
				categories = data
			end
		end
		
		native.setActivityIndicator( false ) -- show busy
			
		local topBoundary = 49
		local bottomBoundary = 49
		local myList = tableView.newList{
			data = categories, 
			default = "images/bgitem.png",
			over = "images/bgitem.png",
			onRelease = onOpenCategories,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				local item = display.newImage("images/item.png")
				item.x = item.width/2
				item.y = item.height/2
				group:insert(item)

				local text = display.newText(row.title, 0, item.y - 8, native.systemFontBold, 16)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				--[[
				text = display.newText(row.description, 0,  36, "Helvetica", 14)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				
				text = display.newText("" .. id, 0,  18, native.systemFontBold, 20)
				text:setTextColor(255, 255, 255)
				text.x = 34 + text.width/2
				group:insert(text)--]]
				
				row.group = group	
				return group
			end
		}
		groupCategories:insert(myList)
		menuGroupTop:toFront()
	end
	-----------------------------------------------------
	--Doc danh muc cac the loai mon an viet nam
	-----------------------------------------------------
	function onLoadCategories(event)
		if categories == nil  then
			local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=CATNAUAN")
			if xmlTree then
				onLoadedCategories(xmlTree)
			else
				native.showAlert( "", "Please check your internet connect!", { "OK"}, onLoadCategories)
			end
		else
			onLoadedCategories(nil)
		end
		closeWaiting()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function setVivibleCategories(isVivible)
		if isVivible then
			textHeader.text = "Thực đơn"
		end
		if groupMenus ~= nil and isVivible then
			groupMenus.isVisible = isVivible
			btnBack.isVisible = isVivible
		else
			btnBack.isVisible = false
			if groupCategories == nil then
				groupCategories = display.newGroup()
				menuGroup:insert(groupCategories)
				menuGroupTop:toFront()
			end
			groupCategories.isVisible = isVivible
			if groupMenus ~= nil then
				groupMenus.isVisible = false
			end
		end
		if popupGroup ~= nil then
			native.cancelWebPopup()
			cleanGroups(popupGroup, 0)
			popupGroup = nil
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function loadMoreApp(xmlTree)
		if moreapp == nil then
			local data={}
			local app = xml:xmlNodes(xmlTree, "app")	
			native.setActivityIndicator( true )
			local n = 1
			for i,xmlNode in pairs(app) do
				if(xmlNode.Name == "MyApp") then
					local myapp = {}
					myapp.appid = xml:xmlValue(xmlNode, "appid")
					myapp.name = xml:xmlValue(xmlNode, "name")
					myapp.description = xml:xmlValue(xmlNode, "description")
					myapp.price = xml:xmlValue(xmlNode, "price")
					myapp.linkdown = xml:xmlValue(xmlNode, "linkdown")
					myapp.logolink = xml:xmlValue(xmlNode, "logolink")
					local download = function() 
						local function networkListener( event )
							if ( event.isError ) then
								print ( "Network error - download failed" )
							else
								myapp.logo =  display.newImage(myapp.appid .. ".png", system.TemporaryDirectory)
								if myapp.group ~= nil then
									myapp.logo.x = myapp.logo.width/2 + 6
									myapp.logo.y = 34
									myapp.group:insert(myapp.logo)
								end
							end
						end
						myapp.logo =  display.newImage(myapp.appid .. ".png", system.TemporaryDirectory)
						if myapp.logo == nil then
							network.download(myapp.logolink, "GET", networkListener, myapp.appid .. ".png", system.TemporaryDirectory )
						else
							if myapp.group ~= nil then
								myapp.logo.x = myapp.logo.width/2 + 6	
								myapp.logo.y =34
								myapp.group:insert(myapp.logo)
							end
						end
					end
					timer.performWithDelay(2, download)
					data[n] = myapp
					n = n + 1
				end
				moreapp = data
			end
		end
		
		native.setActivityIndicator( false ) -- show busy
		
		local topBoundary = 39
		local bottomBoundary = 49
		local myList2 = tblSearch.newList{
			data = moreapp, 
			default = "images/itemA.png",
			over = "images/itemA.png",
			onRelease = onSelectApp,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				
				if math.round(id/2) == id/2 then
					local item = display.newImage("images/itemA01.png")
					item.x = item.width/2
					item.y = item.height/2
					group:insert(item)
				else
					local item = display.newImage("images/itemA02.png")
					item.x = item.width/2
					item.y = item.height/2
					group:insert(item)					
				end
				
				local text = display.newText( row.name, 0,  8, "Helvetica", 18)
				text:setTextColor(255, 255, 255)
				text.x = 78 + text.width/2
				group:insert(text)
				
				text = display.newText( row.description, 0,  42, "Helvetica", 14)
				text:setTextColor(0, 0, 0)
				text.x = 78 + text.width/2
				group:insert(text)
				
				row.group = group	
				if xmlTree == nil then
					row.logo =  display.newImage(row.appid .. ".png", system.TemporaryDirectory)
				end
				if row.logo ~= nil then
					row.logo.x = row.logo.width/2 + 15
					row.logo.y = 25
					group:insert(row.logo)
				end
				return group
			end
		}
		myList2.x = display.contentWidth/2 - 160
		groupTabMoreApp:insert(myList2)
		menuGroupTop:toFront()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function MoreApp(event)
		timer.performWithDelay(20, function(even) 
			if moreapp == nil  then
				if isAndroid then
					local xmlTree = xml:doQuery("http://www.azsoft.com.vn/soft/games/android_moreapp.xml")
					if xmlTree then
						loadMoreApp(xmlTree)
					else
						native.showAlert( "", "Please check your internet connect!", { "OK"}, MoreApp)
					end
				else
					local xmlTree = xml:doQuery("http://www.azsoft.com.vn/soft/games/apple2_moreapp.xml")
					if xmlTree then
						loadMoreApp(xmlTree)
					else
						native.showAlert( "", "Please check your internet connect!", { "OK"}, MoreApp)
					end
				end
			else
				loadMoreApp(nil)
			end
			closeWaiting()
		end, 1)
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onOpenMenuItemInNew(event)
		local self = event.target
		if topNewMenus ~= nil then
			showMenuDetails(topNewMenus[self.id])
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onLoadedTopNew(xmlTree)
		if topNewMenus == nil and stop == false then
			local data={}
			local MENU = xml:xmlNodes(xmlTree, "MENU")	
			native.setActivityIndicator( true )
			local n = 1
			for i,xmlNode in pairs(MENU) do
				if(xmlNode.Name == "item") then
					local game = {}
					game.menuid = xml:xmlValue(xmlNode, "id")
					game.title = xml:xmlValue(xmlNode, "title")
					game.description = xml:xmlValue(xmlNode, "des")
					game.idvideo = xml:xmlValue(xmlNode, "idvideo")
					local download = function() 
						local function networkListener( event )
							if ( event.isError ) then
								print ( "Network error - download failed" )
							else
								if game.group ~= nil then
									game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
									if game.group ~= nil and stop == false  then
										game.logo.x = 4 + game.logo.width/2
										game.logo.y = 4 + game.logo.height/2
										game.group:insert(game.logo)
									elseif game.logo ~= nil and stop then
										game.logo:removeSelf()
									end
								end
							end
						end
						game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
						if game.logo == nil then
							network.download("http://" .. serverConnect .. "/smallimages/" .. game.menuid .. ".png", "GET", networkListener, game.menuid .. ".png", system.TemporaryDirectory )
						else
							if game.group ~= nil  and stop == false  then
								game.logo.x = 4 + game.logo.width/2
								game.logo.y = 4 + game.logo.height/2
								game.group:insert(game.logo)
							elseif game.logo ~= nil and stop then
								game.logo:removeSelf()
							end
						end
					end
					timer.performWithDelay(2, download)
					data[n] = game
					n = n + 1
					print("Co ma")
				end
				topNewMenus = data
			end
		end
		
		native.setActivityIndicator( false ) -- show busy
			
		local topBoundary = 49
		local bottomBoundary = 49
		local myList = tblTopNew.newList{
			data = topNewMenus, 
			default = "images/bgitem.png",
			over = "images/bgitem.png",
			onRelease = onOpenMenuItemInNew,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				local item = display.newImage("images/item.png")
				item.x = item.width/2
				item.y = item.height/2
				group:insert(item)

				local text = display.newText(row.title, 0,  10, native.systemFontBold, 15)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				text = display.newText(row.description, 0,  36, "Helvetica", 14)
				text:setTextColor(200, 200, 200)
				text.x = 68 + text.width/2
				group:insert(text)
				
				row.group = group	
				return group
			end
		}
		--myList.x = 0
		groupTabmenusNew:insert(myList)
		menuGroupTop:toFront()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function loadTopNewMenuItem(event)
		if topNewMenus == nil  then
			local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=TOPNEWMENU")
			if xmlTree then
				onLoadedTopNew(xmlTree)
			else
				--native.showAlert( "", "Please check your internet connect!", { "OK"}, loadTopNewMenuItem)
			end
		else
			onLoadedTopNew(nil)
		end
		closeWaiting()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function setVisibleTopNew(isVivible)
		btnBack.isVisible = false
		if isVivible then
			textHeader.text = "Món mới"
		end
		if groupTabmenusNew == nil and isVivible then
			groupTabmenusNew = display.newGroup()
			menuGroup:insert(groupTabmenusNew)
			showWaiting()
			theTimer = timer.performWithDelay(250, function(event)
				loadTopNewMenuItem()
			end, 1)
						
			menuGroupTop:toFront()
		end
		if groupTabmenusNew ~= nil then
			groupTabmenusNew.isVisible = isVivible
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onOpenMenuItemInLove(event)
		local self = event.target
		if listMenuYeuThich ~= nill then
			showMenuDetails(listMenuYeuThich[self.id])
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onLoadedYeuThich(xmlTree)
		if listMenuYeuThich == nil and stop == false then
			local data={}
			local MENU = xml:xmlNodes(xmlTree, "MENU")	
			native.setActivityIndicator( true )
			local n = 1
			for i,xmlNode in pairs(MENU) do
				if(xmlNode.Name == "item") then
					local game = {}
					game.menuid = xml:xmlValue(xmlNode, "id")
					game.title = xml:xmlValue(xmlNode, "title")
					game.description = xml:xmlValue(xmlNode, "des")
					game.idvideo = xml:xmlValue(xmlNode, "idvideo")
					game.yeuthich = true
					local download = function() 
						local function networkListener( event )
							if ( event.isError ) then
								print ( "Network error - download failed" )
							else
								game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
								if game.group ~= nil and stop == false  then
									game.logo.x = 4 + game.logo.width/2
									game.logo.y = 4 + game.logo.height/2
									game.group:insert(game.logo)
								elseif game.logo ~= nil and stop then
									game.logo:removeSelf()
								end
							end
						end
						game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
						if game.logo == nil then
							network.download("http://" .. serverConnect .. "/smallimages/" .. game.menuid .. ".png", "GET", networkListener, game.menuid .. ".png", system.TemporaryDirectory )
						else
							if game.group ~= nil  and stop == false  then
								game.logo.x = 4 + game.logo.width/2
								game.logo.y = 4 + game.logo.height/2
								game.group:insert(game.logo)
							elseif game.logo ~= nil and stop then
								game.logo:removeSelf()
							end
						end
					end
					timer.performWithDelay(2, download)
					data[n] = game
					n = n + 1
				end
				listMenuYeuThich = data
			end
		end
		
		
		native.setActivityIndicator( false ) -- show busy
			
		local topBoundary = 49
		local bottomBoundary = 49
		local myList = tblYeuThich.newList{
			data = listMenuYeuThich, 
			default = "images/bgitem.png",
			over = "images/bgitem.png",
			onRelease = onOpenMenuItemInLove,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				local item = display.newImage("images/item.png")
				item.x = item.width/2
				item.y = item.height/2
				group:insert(item)

				local text = display.newText(row.title, 0,  10, native.systemFontBold, 15)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				text = display.newText(row.description, 0,  36, "Helvetica", 14)
				text:setTextColor(200, 200, 200)
				text.x = 68 + text.width/2
				group:insert(text)
				
				row.logo =  display.newImage(row.menuid .. ".png", system.TemporaryDirectory)
				if row.logo ~= nil then
					row.logo.x = 4 + row.logo.width/2
					row.logo.y = 4 + row.logo.height/2
					group:insert(row.logo)
				end
				row.group = group	
				return group
			end
		}
		--myList.x = 0
		groupTabYeuThich:insert(myList)
		menuGroupTop:toFront()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function loadYeuThich(event)
		if listMenuYeuThich == nil then
			print(memberid)
			local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=NAYEUTHICH&memberid=" .. memberid)
			if xmlTree then
				onLoadedYeuThich(xmlTree)
			else
				native.showAlert( "", "Please check your internet connect!", { "OK"}, loadYeuThich)
			end
		else
			onLoadedYeuThich(nil)
		end
		closeWaiting()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function setVisibleYeuThich(isVivible)
		btnBack.isVisible = false
		if isVivible then
			textHeader.text = "Chuyên mục yêu thích"
		else
			if menuGroupLogin ~= nil then
				cleanGroups(menuGroupLogin, 0)
				menuGroupLogin = nil
			elseif menuGroupRegister ~= nil then
				cleanGroups(menuGroupRegister, 0)
				menuGroupRegister = nil
			end
		end
		if groupTabYeuThich == nil and isVivible then
			groupTabYeuThich = display.newGroup()
			menuGroup:insert(groupTabYeuThich)
			if memberid == nil then
				groupFormLogin = display.newGroup()
				groupTabYeuThich:insert(groupFormLogin)
				--Thong bao can login truoc khi su dung
				lblWarring = display.newImage("images/lblWarring.png")
				lblWarring.x = display.contentWidth/2
				lblWarring.y = display.contentHeight/2
				groupFormLogin:insert(lblWarring)
			
				btnLogin = ui.newButton{
					default = "images/btnLogin.png",
					over = "images/btnLoginOver.png",
					onRelease = function(event)
						if menuGroupRegister == nil and menuGroupLogin == nil then
							showFormLogin(groupFormLogin, "YeuThich")
						end
					end
				}
				btnLogin.x = display.contentWidth/2 + btnLogin.width/2 + 5
				btnLogin.y = display.contentHeight/2  + 68
				groupFormLogin:insert(btnLogin)
				
				btnRegister = ui.newButton{
					default = "images/btnRegister.png",
					over = "images/btnRegisterOver.png",
					onRelease = function(event)
						if menuGroupRegister == nil and menuGroupLogin == nil then
							showFormRegister(groupFormLogin, "YeuThich")
						end
					end
				}
				btnRegister.x = display.contentWidth/2 - btnRegister.width/2 - 5
				btnRegister.y = display.contentHeight/2 + 68
				groupFormLogin:insert(btnRegister)
			else
				showWaiting()
				theTimer = timer.performWithDelay(250, function(event)
					loadYeuThich()
				end, 1)
			end
			
			menuGroupTop:toFront()
		end
		
		if groupTabYeuThich ~= nil then
			groupTabYeuThich.isVisible = isVivible
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function onOpenMenuItemInSearch(event)
		local self = event.target
		if listSearch ~= nill then
			native.setKeyboardFocus( nil )
			if headerSearch ~= nil then
				txtSearch.isVisible = false
				headerSearch.isVisible = false
			end
			showMenuDetails(listSearch[self.id])
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function doLoadSearch(xmlTree)
		if listSearch == nil and stop == false then
			local data={}
			local MENU = xml:xmlNodes(xmlTree, "MENU")	
			native.setActivityIndicator( true )
			local n = 1
			for i,xmlNode in pairs(MENU) do
				if(xmlNode.Name == "item") then
					local game = {}
					game.menuid = xml:xmlValue(xmlNode, "id")
					game.title = xml:xmlValue(xmlNode, "title")
					game.description = xml:xmlValue(xmlNode, "des")
					game.idvideo = xml:xmlValue(xmlNode, "idvideo")
					local download = function() 
						local function networkListener( event )
							if ( event.isError ) then
								print ( "Network error - download failed" )
							else
								game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
								if game.group ~= nil and stop == false  then
									game.logo.x = 4 + game.logo.width/2
									game.logo.y = 4 + game.logo.height/2
									game.group:insert(game.logo)
								elseif game.logo ~= nil and stop then
									game.logo:removeSelf()
								end
							end
						end
						game.logo =  display.newImage(game.menuid .. ".png", system.TemporaryDirectory)
						if game.logo == nil then
							network.download("http://" .. serverConnect .. "/smallimages/" .. game.menuid .. ".png", "GET", networkListener, game.menuid .. ".png", system.TemporaryDirectory )
						else
							if game.group ~= nil  and stop == false  then
								game.logo.x = 4 + game.logo.width/2
								game.logo.y = 4 + game.logo.height/2
								game.group:insert(game.logo)
							elseif game.logo ~= nil and stop then
								game.logo:removeSelf()
							end
						end
					end
					timer.performWithDelay(2, download)
					data[n] = game
					n = n + 1
				end
				listSearch = data
			end
		end
		native.setActivityIndicator( false ) -- show busy
			
		local topBoundary = 49
		local bottomBoundary = 49
		local myList = tblSearch.newList{
			data = listSearch, 
			default = "images/bgitem.png",
			over = "images/bgitem.png",
			onRelease = onOpenMenuItemInSearch,
			top = topBoundary,
			bottom = bottomBoundary,
			nil,
			callback=function(row, id) 
				local group = display.newGroup()
				local item = display.newImage("images/item.png")
				item.x = item.width/2
				item.y = item.height/2
				group:insert(item)

				local text = display.newText(row.title, 0,  10, native.systemFontBold, 15)
				text:setTextColor(255, 255, 255)
				text.x = 68 + text.width/2
				group:insert(text)
				
				text = display.newText(row.description, 0,  36, "Helvetica", 14)
				text:setTextColor(200, 200, 200)
				text.x = 68 + text.width/2
				group:insert(text)
				
				row.group = group	
				return group
			end
		}
		--myList.x = 0
		groupTabSearch:insert(myList)
		menuGroupTop:toFront()
		if headerSearch ~= nil then
			headerSearch:toFront()
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function slip(str, key)
		local k = 1
		local index = 1
		local data = {}
		while index > 0 do
			local i, j = string.find(str, key, k)
			if i == nil then
				data[index] = str:sub(k)
				index = -1
			else
				--print(i .. " - " .. j)
				local si = str:sub(k, i - 1)
				data[index] = si
				k = j + 1
			end
			index = index + 1
		end
		return data
	end
	
	function doSearch(svalue)
		local data = slip(svalue, " ")
		svalue = ""
		local i = 1
		while i < #data + 1 do
			svalue = svalue .. data[i] .. "%20"
			i = i + 1
		end
		print(svalue)
		
		local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=NASEARCH&svalue=" .. svalue)
		if xmlTree then
			if groupTabSearch ~= nil then
				cleanGroups(groupTabSearch, 0)
				menuGroupLogin = nil
			end
			listSearch = nil
			groupTabSearch = display.newGroup()
			menuGroup:insert(groupTabSearch)
			doLoadSearch(xmlTree)
		else
			native.showAlert( "", "Please check your internet connect!", { "OK"}, loadTopHotmenus)
		end
		closeWaiting()
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function setVisibleSearch(isVivible)
		btnBack.isVisible = false
		if isVivible then
			textHeader.text = "Chuyên mục yêu thích"
		end
		if headerSearch == nil and isVivible then
			headerSearch = display.newGroup()
			menuGroup:insert(headerSearch)
			--Textbox email
			if system.getInfo( "environment" ) == "simulator" then
				txtSearch = display.newRect(12, 10, 268, 28)
				txtSearch:setFillColor(200, 200, 200)
				headerSearch:insert(txtSearch)
			else
				txtSearch = native.newTextField(12, 10, 268, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtSearch.font = native.newFont( native.systemFontBold, inputFontSize )
				txtSearch.inputType = "search"
				headerSearch:insert(txtSearch)
			end
			
			btnSearch = ui.newButton{
				default = "images/btnSearch.png",
				over = "images/btnSearchOver.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						if system.getInfo( "environment" ) ~= "simulator" and (txtSearch.text == nil or txtSearch.text == "") then
							native.showAlert( "", "Xin vui lòng nhập từ khóa tìm kiếm!", { "OK"}, onComplete)
						else
							local svalue = "mon an viet nam"
							if system.getInfo( "environment" ) ~= "simulator" then
								svalue = txtSearch.text
							end
							doSearch(svalue)
						end
					end, 1)
				end
			}
			btnSearch.x = 300
			btnSearch.y = 25
			headerSearch:insert(btnSearch)
		
			menuGroupTop:toFront()
			headerSearch:toFront()
		end
		if groupTabSearch ~= nil then
			groupTabSearch.isVisible = isVivible
		end
		if headerSearch ~= nil then
			txtSearch.isVisible = isVivible
			headerSearch.isVisible = isVivible
			headerSearch:toFront()
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function setVivibleTabAbout(isVivible)
		btnBack.isVisible = false
		if isVivible then
			textHeader.text = "1001 Món ăn Việt Nam"
		end
		if groupTabAbout == nil then
			groupTabAbout = display.newGroup()
			menuGroup:insert(groupTabAbout)
			
			local bg = display.newImage("images/bgAbout.png")
			bg.x = display.contentWidth/2
			bg.y = display.contentHeight/2
			groupTabAbout:insert(bg)
			
			menuGroupTop:toFront()
		end
		groupTabAbout.isVisible = isVivible
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------	
	function setVisibleMoreApp(isVivible)
		if groupTabMoreApp == nil and isVivible then
			groupTabMoreApp = display.newGroup()
			menuGroup:insert(groupTabMoreApp)
			showWaiting()
			MoreApp()
			
			menuGroupTop:toFront()
		end
		if groupTabMoreApp ~= nil then
			groupTabMoreApp.isVisible = isVivible
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function showScreen(event)
		local t = event.target
		local phase = event.phase
		if phase == "ended" then
			if t.id == 1 then
				setVisibleTopNew(false)
				setVisibleYeuThich(false)
				setVisibleSearch(false)
				setVivibleTabAbout(false)
				setVivibleCategories(true)
			elseif t.id == 2 then
				setVivibleCategories(false)
				setVisibleYeuThich(false)
				setVisibleSearch(false)
				setVivibleTabAbout(false)
				setVisibleTopNew(true)
			elseif t.id == 3 then
				setVivibleCategories(false)
				setVisibleTopNew(false)
				setVisibleSearch(false)
				setVivibleTabAbout(false)
				setVisibleYeuThich(true)
			elseif t.id == 4 then
				setVivibleCategories(false)
				setVisibleTopNew(false)
				setVisibleYeuThich(false)
				setVivibleTabAbout(false)
				setVisibleSearch(true)
			elseif t.id == 5 then
				setVivibleCategories(false)
				setVisibleTopNew(false)
				setVisibleYeuThich(false)
				setVisibleSearch(false)
				setVivibleTabAbout(true)
			end 
			tabBar.selected(t)
		end
		return true
	end
	
	function drawScreen()
		bg = display.newImage("images/bg.png")
		bg.x = display.contentWidth/2
		bg.y = display.contentHeight/2
		menuGroup:insert(bg)
		
		menuGroup:insert(menuGroupTop)
		navBar = display.newImage("images/navBar.png", 0, 0, true)
		navBar.x = display.contentWidth*.5
		navBar.y = navBar.height*0.5
		menuGroupTop:insert(navBar)
		
		--[[btnFb = ui.newButton{
				default = "images/btnFb.png",
				over = "images/btnFbOver.png",
				onRelease = function(event)
					onShareFaceBook()
				end
			}
		btnFb.x = display.contentWidth - btnFb.width/2 - 2
		btnFb.y = navBar.y
		menuGroupTop:insert(btnFb)--]]
		
		btnBack = ui.newButton{
			default = "images/btnBack.png",
			over = "images/btnBackOver.png",
			onRelease = function(event)
				if popupGroup ~= nil then
					native.cancelWebPopup()
					cleanGroups(popupGroup, 0)
					popupGroup = nil
				else
					if groupMenus ~= nil and groupMenus.isVisible then
						cleanGroups(groupMenus, 0)
						groupMenus = nil
						setVivibleCategories(true)
					end
				end
			end
		}
		btnBack.x = btnBack.width/2
		btnBack.y = navBar.y
		menuGroupTop:insert(btnBack)
		
		--Caption
		textHeader = display.newText("1001 Mon an Viet", 0, navBar.y - 10, native.systemFontBold, 14)
		textHeader:setTextColor(255, 255, 255)
		textHeader.x = display.contentWidth*.5
		menuGroupTop:insert(textHeader)
		
		tabBar = viewController.newTabBar{
			background = "images/tabBar.png",
			tabs = {"", "", "", "", ""},
			default = {"images/tab1.png", "images/tab2.png", "images/tab3.png", "images/tab4.png", "images/tab5.png"},
			over = {"images/tab1Over.png", "images/tab2Over.png", "images/tab3Over.png", "images/tab4Over.png", "images/tab5Over.png"},
	
			onRelease = showScreen
		}
		menuGroupTop:insert(tabBar)
		tabBar.selected()
		
		setVivibleCategories(true)
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	drawScreen()
	-----------------------------------------------------
	--
	-----------------------------------------------------
	loading()
	-----------------------------------------------------
	--
	-----------------------------------------------------
	loadLogin()
	--showWaiting()
	--showMenuDetails(1, "Bun reu chay", "Mon chay")
	theTimer = timer.performWithDelay(250, function(event)
		onLoadCategories()
	end, 1)
	-----------------------------------------------------
	--
	-----------------------------------------------------		
	function cleanGroups (curGroup, level)
		if curGroup.numChildren then
			while curGroup.numChildren > 0 do
				cleanGroups (curGroup[curGroup.numChildren], level+1)
			end
			if level > 0 then
				curGroup:removeSelf()
				curGroup = nil
			end
		else
			if curGroup then
				curGroup:removeSelf()
				curGroup = nil
			end
			return
		end
	end	
	unloadMe = function()
		stop = true
		native.cancelWebPopup()
		if theTimer then
			timer.cancel(theTimer)
		end
	end
	
	return menuGroup
end